import {
  getStorage,
  setStorage,
  getSetting,
  getUserInfo,
  login
} from '@/utils/wx'

export default {
  methods: {
    checkTime (i) {
      if (i < 10) {
        i = `0${i}`
      }
      return i
    },
    timeFilter (time) {
      const date = new Date(time * 1000)
      return `${this.checkTime(date.getMonth() + 1)}月${this.checkTime(date.getDate())}日 ${this.checkTime(date.getHours())}:${this.checkTime(date.getMinutes())}`
    },
    /**
     * 重置data
     */
    resetData () {
      Object.assign(this.$data, this.$options.data())
    },
    async getOpenId () {
      let openId = ''
      try {
        openId = await getStorage('openId')
      } catch (err) {
        openId = ''
      }
      if (openId) {
        // 创建玩家
        let hasUpserted = false
        try {
          hasUpserted = await getStorage('hasUpserted')
        } catch (err) {
          hasUpserted = false
        }
        // 低版本做兼容，判断没有用户信息，则主动上送用户信息
        // 如果同一会话已经上传了用户信息，则不再上传
        if (!hasUpserted) {
          const ret = await this.$store.dispatch('getPlayerInfo', {
            noToast: true,
            playerid: openId
          })
          if (!ret.nickname) {
            await this.upsertPlayer(openId)
          }
          setStorage('hasUpserted', true)
        }
        return Promise.resolve(openId)
      } else {
        const res = await login()
        if (res.code) {
          // 上送code，获取openId
          const authRes = await this.$store.dispatch('wechatAuth', res.code)
          if (authRes) {
            const openId = authRes.openid
            setStorage('openId', openId)
            await this.upsertPlayer(openId)
            return Promise.resolve(openId)
          }
        }
      }
    },
    /**
     * 获取用户信息
     */
    async getUserInfo () {
      try {
        const res = await getUserInfo()
        return Promise.resolve(res)
      } catch (err) {
        return Promise.reject(err)
      }
    },
    async upsertPlayer (openId) {
      let userRes = null
      try {
        userRes = await this.getUserInfo()
      } catch (err) {
        userRes = null
      }
      // 获取我的上级
      let parentId = null
      try {
        parentId = await getStorage('parentId')
      } catch (err) {
        parentId = null
      }

      if (userRes) {
        const userInfo = userRes.userInfo
        await this.$store.dispatch('doPlayerUpsert', {
          playerid: openId,
          nickname: userInfo.nickName,
          headimgurl: userInfo.avatarUrl,
          sex: userInfo.gender,
          city: userInfo.city,
          province: userInfo.province,
          country: userInfo.country,
          parentid: parentId
        })
      }
    },
    /**
     * 查看是否授权
     */
    async checkUserInfo () {
      try {
        const res = await getSetting()
        if (res.authSetting['scope.userInfo']) {
          return Promise.resolve(true)
        }
      } catch (err) {
        return Promise.reject(err)
      }
    },
    /**
     * 判断授权并跳转
     */
    async checkAuth () {
      const hasUserInfo = await this.checkUserInfo()
      if (!hasUserInfo) {
        wx.navigateTo({
          url: `/pages/auth/main`
        })
        return false
      }
      return true
    },
    /**
     * 检查小程序更新
     */
    checkUpdate () {
      if (wx.getUpdateManager) {
        const updateManager = wx.getUpdateManager()
        updateManager.onUpdateReady(() => {
          wx.showModal({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success: (res) => {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate()
              }
            }
          })
        })
      } else {
        // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
        // wx.showModal({
        //   title: '提示',
        //   content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
        // })
      }
    }
  }
}
